package com.newear.util;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;

import java.io.IOException;

/**
 * Created by josan on 2018/5/29
 */

public class MyMediaPlayer {

    private MyMediaPlayer() {
    }
    public static MyMediaPlayer getInstance() {
        return MyMediaPlayerHolder.instance;
    }
    private static class MyMediaPlayerHolder {
        private static final MyMediaPlayer instance = new MyMediaPlayer();
    }

    /**
     * 播放语音
     * @param context
     * @return
     */
    public MediaPlayer playing(Context context, int mp3Id) {
        MediaPlayer player = null;
        try {
            player = MediaPlayer.create(context, mp3Id);//创建mediaplayer对象
            // todo 为了不影响测试，关闭了语音，上线需要打开
            player.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return player;
    }

    private AssetManager assetManager;
    public MediaPlayer playing(Context context, String fileName) {
        MediaPlayer player = null;
        try {
            player = new MediaPlayer();
            assetManager = context.getAssets();
            player.reset();
            AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
            player.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(),
                    fileDescriptor.getStartOffset());
            fileDescriptor.close();
            player.prepare();
            final MediaPlayer finalPlayer = player;
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    finalPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return player;
    }

    public MediaPlayer playing2(Context context, int mp3Id) {
        try {
            MediaPlayer mp = new MediaPlayer();
            AssetFileDescriptor file = context.getResources().openRawResourceFd(mp3Id);
            try {
                mp.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
                        file.getLength());
                mp.prepare();
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mp.setVolume(0.5f, 0.5f);
            mp.setLooping(false);
            mp.start();
            return mp;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
